<template>
  <div class="container">
    <el-dialog
      :title="dialog.dialogType === 'edit' ? '修改费用单' : '创建费用单'"
      :visible.sync="dialog.dialogVisible"
      width="90%"
      center
      @open="getData"
      :lock-scroll="true"
      @close="closeDialog"
    >
      <div class="top">
        <el-form label-width="100px" label-position="left">
          <el-form-item label="供应商：">
            <el-select
              v-model="inside.value"
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              placeholder="请选择供应商"
              :remote-method="insideRemoteMethod"
              :loading="inside.loading"
              @change="onSupplier(inside.value)"
            >
              <el-option
                v-for="item in inside.list"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配送中心：">
            <el-select
              v-model="distribution.value"
              :multiple="false"
              filterable
              remote
              reserve-keyword
              placeholder="请选择配送中心"
              :remote-method="insideDistribution"
              :loading="distribution.loading"
              @change="onrdc(distribution.value)"
            >
              <el-option
                v-for="item in distribution.list"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="采购员：">
            <el-select
              v-model="purchase.value"
              :multiple="false"
              filterable
              remote
              center
              reserve-keyword
              placeholder="请选择采购员"
              :remote-method="insidePurchaseMethod"
              :loading="inside.loading"
              @change="onBuyer(purchase.value)"
            >
              <el-option
                v-for="item in purchase.list"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单据类型：">
            <el-select
              v-model="formData.bill_type"
              placeholder="请选择单据类型"
            >
              <el-option
                v-for="item in billTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收取反向：">
            <el-select v-model="formData.mode" placeholder="请选择收取反向">
              <el-option
                v-for="item in modeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单据备注：">
            <el-input
              style="width: 400px;"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="formData.notes"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="费用项：">
            <el-select v-model="expense" placeholder="请选择费用">
              <el-option
                v-for="item in expenseTypeList"
                :key="item.id"
                :label="item.type_name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-button @click="addExpenseType" type="primary">添加</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="name"
          label="费用名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="type_code"
          label="编码"
          align="center"
        ></el-table-column>
        <el-table-column label="金额" align="center">
          <template slot-scope="scope">
            <el-input-number
              size="small"
              :controls="false"
              v-model="scope.row.amount"
            ></el-input-number>
          </template>
        </el-table-column>

        <el-table-column label="备注" align="center">
          <template slot-scope="scope">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="scope.row.notes"
            >
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="remove(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  readExpense,
  addExpense,
  editExpense,
  expenseType
} from "@/api/expenseDoc/expenseDocList";
import { selectRdcDataNew } from "@/api/permission/adminlist";
import {
  selectBuyerList,
  selectSupplierList
} from "@/api/putStorage/superPurchaseList";
export default {
  props: {
    dialog: Object
  },
  data() {
    return {
      inside: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      },
      purchase: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      },

      distribution: {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: ""
      },
      billTypeList: [
        {
          value: 1,
          label: "生鲜"
        },
        {
          value: 2,
          label: "商超"
        }
      ],
      modeList: [
        {
          value: 1,
          label: "应收"
        },
        {
          value: 2,
          label: "应付"
        }
      ],
      expenseTypeList: [],
      formData: {
        supplier_id: "",
        bill_type: "",
        rdc_code: "",
        buyer_id: "",
        buyer_code: "",
        buyer_name: "",
        mode: "",
        notes: ""
      },
      expense: "",
      tableData: []
    };
  },
  created() {},
  methods: {
    addExpenseType() {
      if (this.expense) {
        let arr = this.expenseTypeList.filter(res => {
          return res.id == this.expense;
        });
        if (this.tableData.length > 0) {
          let boolArr = this.tableData.filter(res => {
            return res.type_id == arr[0].id;
          });
          if (boolArr.length > 0) {
            this.$message({
              message: "该费用项已添加",
              type: "info"
            });
          } else {
            this.tableData.push({
              type_id: arr[0].id,
              type_code: arr[0].type_code,
              amount: 0,
              notes: "",
              name: arr[0].type_name
            });
          }
        } else {
          this.tableData.push({
            type_id: arr[0].id,
            type_code: arr[0].type_code,
            amount: 0,
            notes: "",
            name: arr[0].type_name
          });
        }
      } else {
        this.$message({
          message: "请选择费用项",
          type: "info"
        });
      }
    },
    getData() {
      if (this.dialog.dialogType == "edit") {
        let data = {
          id: this.dialog.id
        };
        readExpense(data).then(res => {
          if (res.code == 0) {
            res.data.detail.forEach(item => {
              this.tableData.push({
                type_id: item.type_id,
                type_code: item.type_code,
                amount: item.amount,
                notes: item.notes,
                name: item.type_name
              });
            });
            this.formData = {
              supplier_id: res.data.expense.supplier_id,
              bill_type: res.data.expense.bill_type,
              rdc_code: res.data.expense.rdc_code,
              buyer_id: res.data.expense.buyer_id,
              buyer_code: res.data.expense.buyer_code,
              buyer_name: res.data.expense.buyer_name,
              mode: res.data.expense.mode,
              notes: res.data.expense.notes
            };
            this.inside.value = res.data.expense.supplier_name;
            this.purchase.value = res.data.expense.buyer_name;
            this.distribution.value = res.data.expense.rdc_name;
          }
        });
      }
      this.getSupplierList();
      this.getPurchaseList();
      this.getDistribution();
      this.getExpenseType();
    },
    getExpenseType() {
      expenseType().then(res => {
        this.expenseTypeList = res.data.list;
      });
    },
    // 嵌套搜索供应商数据
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //获取供应商数据
    getSupplierList(query = "") {
      let data = {
        name: query,
        page: 1,
        limit: 100
      };
      this.inside.loading = true;
      selectSupplierList(data).then(res => {
        this.inside.list = res.data.paginate.data.map(item => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}`
          };
        });
        this.inside.loading = false;
      });
    },
    onSupplier(e) {
      this.formData.supplier_id = e;
    },
    // 嵌套搜索采购员数据
    insidePurchaseMethod(query) {
      if (query !== "") {
        this.getPurchaseList(query);
      } else {
        this.purchase.options = [];
      }
    },
    getPurchaseList(query = "") {
      let data = {
        name: query,
        page: 1,
        limit: 100
      };
      this.purchase.loading = true;
      selectBuyerList(data).then(res => {
        this.purchase.list = res.data.paginate.data.map(item => {
          return {
            value: `${item.id}`,
            label: `${item.name}`,
            code: `${item.code}`
          };
        });
        this.purchase.loading = false;
      });
    },
    onBuyer(e) {
      let arr = this.purchase.list.filter(res => {
        return res.value == e;
      });
      this.formData.buyer_id = arr[0].value;
      this.formData.buyer_code = arr[0].code;
      this.formData.buyer_name = arr[0].label;
    },
    //搜索配送中心
    insideDistribution(query) {
      if (query !== "") {
        this.getDistribution(query);
      } else {
        this.procurement.options = [];
      }
    },
    getDistribution(query = "") {
      let data = {
        code_or_name: query,
        page: 1,
        limit: 200
      };
      this.distribution.loading = true;
      selectRdcDataNew(data).then(res => {
        this.distribution.list = res.data.paginate.data.map(item => {
          return {
            value: `${item.d_code}`,
            label: `${item.d_name}`
          };
        });
        this.distribution.loading = false;
      });
    },
    onrdc(e) {
      let arr = this.purchase.list.filter(res => {
        return res.value == e;
      });
      this.formData.rdc_code = e;
    },
    //删除
    remove(scope) {
      let index = scope.$index;
      this.tableData.splice(index, 1);
    },
    //提交
    confirm() {
      //   if (this.tableData.length == 0) {
      //     this.$message({
      //       message: "请添加费用项",
      //       type: "info"
      //     });
      //     return
      //   }
      let arr = [];
      this.tableData.forEach(res => {
        arr.push({
          type_id: res.type_id,
          amount: res.amount,
          notes: res.notes
        });
      });
      let data = {
        supplier_id: this.formData.supplier_id,
        bill_type: this.formData.bill_type,
        rdc_code: this.formData.rdc_code,
        buyer_id: this.formData.buyer_id,
        buyer_code: this.formData.buyer_code,
        buyer_name: this.formData.buyer_name,
        mode: this.formData.mode,
        notes: this.formData.notes,
        detail: JSON.stringify(arr)
      };
      if (this.dialog.dialogType == "edit") {
        data.id = this.dialog.id;
        editExpense(data).then(res => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: res.msg || res.message
            });
            this.$emit("upData");
            this.closeDialog();
          }
        });
      } else {
        addExpense(data).then(res => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: res.msg || res.message
            });
            this.$emit("upData");
            this.closeDialog();
          }
        });
      }
    },
    //取消
    closeDialog() {
      this.expenseTypeList = [];
      this.formData = {
        supplier_id: "",
        bill_type: "",
        rdc_code: "",
        buyer_id: "",
        buyer_code: "",
        buyer_name: "",
        mode: "",
        notes: ""
      };
      this.inside = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      };
      this.purchase = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false
      };

      this.distribution = {
        options: [],
        value: "",
        list: [],
        loading: false,
        id: ""
      };
      this.expense = "";
      this.tableData = [];
      this.dialog.dialogVisible = false;
    }
  }
};
</script>
<style scoped>
.top {
  position: relative;
  /* height: 40px; */
}
.main {
  display: flex;
  justify-content: center;
}
.add {
  margin: 10px 0;
  margin-left: auto;
}
</style>
